package com.ict.web.task;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ict.common.utils.StringUtils;
import com.ict.web.domain.ProjectSystemInfo;
import com.ict.web.dto.ProjectSystemInfoDto;
import com.ict.web.service.ProjectSystemInfoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.*;

/**
 * 异步工厂（产生任务用）
 * @author xc
 */
public class RefreshCloudTaskAsyncFactory {

    private static final Logger logger =
            LoggerFactory.getLogger(RefreshCloudTaskAsyncFactory.class);
    //云管平台对接接口
    public static final String CLOUD_URL="http://100.100.104.12:21102/rest/dspApi/1/ywxt?pageSize=1&pageNo=1";

    /**
     * 同步项目系统信息数据
     *
     * @return 任务task
     */
    public static TimerTask asyncStatus(final ProjectSystemInfoService projectSystemInfoService) {

        return new TimerTask() {
            @Override
            @Transactional(rollbackFor = Exception.class)
            public void run() {
                logger.error("------同步项目数据--------");
                Map<String, String> headersDept = new HashMap<>();
                headersDept.put("appKey", "968178584004853760");
                String infoList = HttpUtil.createPost(CLOUD_URL).addHeaders(headersDept).execute().body();
                JSONObject obj= JSONObject.parseObject(infoList);
                String JsonStr = obj.get("data").toString();
                List<ProjectSystemInfoDto> projectSystemInfoList = JSONArray.parseArray(JsonStr, ProjectSystemInfoDto.class);
                //同步项目系统信息数据
                List<ProjectSystemInfo> updateList = new ArrayList<>();
                List<ProjectSystemInfo> saveList = new ArrayList<>();
                projectSystemInfoList.stream().forEach(s->{
                    //新增数据
                    if(StringUtils.isNotNull(s.getUpdated_time())){
                        ProjectSystemInfo projectSystemInfo = projectSystemInfoService.getById(s.getId());
                        projectSystemInfo.setId(Long.valueOf(s.getId()));
                        projectSystemInfo.setProId(s.getPro_id());
                        projectSystemInfo.setProName(s.getPro_name());
                        projectSystemInfo.setDepartId(s.getDepart_id());
                        projectSystemInfo.setAppId(s.getApp_id());
                        projectSystemInfo.setAppName(s.getApp_name());
                        projectSystemInfo.setUpdatedTime(LocalDateTime.ofEpochSecond(Long.valueOf(s.getUpdated_time()) / 1000, 0, ZoneOffset.ofHours(8)));
                        projectSystemInfo.setAppCreatedUser(s.getApp_created_user());
                        projectSystemInfo.setAppIsCloud(s.getApp_is_cloud().equals("true")?true:false);
                        projectSystemInfo.setCreatedTime(s.getCreated_time()!=null?LocalDateTime.ofEpochSecond(Long.valueOf(s.getCreated_time()) / 1000, 0, ZoneOffset.ofHours(8)):null);
                        updateList.add(projectSystemInfo);
                        //更新数据
                    }else if(StringUtils.isNull(s.getUpdated_time())&&StringUtils.isNotNull(s.getCreated_time())){
                        ProjectSystemInfo info = new ProjectSystemInfo();
                        info.setId(Long.valueOf(s.getId()));
                        info.setProId(s.getPro_id());
                        info.setProName(s.getPro_name());
                        info.setDepartId(s.getDepart_id());
                        info.setAppId(s.getApp_id());
                        info.setAppName(s.getApp_name());
                        info.setCreatedTime(LocalDateTime.parse(s.getCreated_time()));
                        info.setAppCreatedUser(s.getApp_created_user());
                        info.setAppIsCloud(s.getApp_is_cloud().equals("true")?true:false);
                        info.setCreatedTime(LocalDateTime.ofEpochSecond(Long.valueOf(s.getCreated_time()) / 1000, 0, ZoneOffset.ofHours(8)));
                        saveList.add(info);
                    }
                });
                if(StringUtils.isNotEmpty(updateList)){
                    projectSystemInfoService.saveOrUpdateBatch(updateList);
                }
                if(StringUtils.isNotEmpty(saveList)){
                    projectSystemInfoService.saveBatch(saveList);
                }
                logger.info("同步项目系统信息数据:已同步完成");
            }
        };
    }
}
